<template>
  <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" :append-to-body="true" @close="close">
    <!-- 表单内容 -->
    <el-form ref="FormModel" label-width="auto" :model="FormModel" :rules="rules" status-icon>
      <el-form-item label="角色名称" prop="name">
        <el-input v-model="FormModel.name" style="width:300px" size="mini" placeholder="角色名称" />
      </el-form-item>
      <el-form-item label="启用">
        <el-switch v-model="FormModel.state" size="mini" />
      </el-form-item>
      <el-form-item label="角色描述" prop="description">
        <el-input v-model="FormModel.description" type="textarea" :rows="5" style="width:300px" size="mini" placeholder="角色描述" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="mini" @click="confirm">确定</el-button>
        <el-button size="mini" @click="close">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { addRole } from '@/api/role.js'
export default {
  name: 'Roledialog',
  data() {
    return {
      showDialog: false,
      defaultModel: {
        name: '', // 角色名称
        description: '', // 角色描述
        state: false // 是否启用
      },
      FormModel: { ...this.defaultModel },
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 确认添加角色
    async confirm() {
      this.$refs.FormModel.validate() // 表单再次校验
      this.FormModel.state = this.FormModel.state ? 1 : 0
      const res = await addRole(this.FormModel)
      console.log(res)
      this.close()
      this.$emit('Refresh')
    },
    // 关闭弹框
    close() {
      this.FormModel = { ...this.defaultModel } // 恢复默认空白数据
      this.$refs.FormModel.resetFields() // 重置表单校验
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog .el-dialog__body{
      display: flex;
      justify-content: center;
      align-items: center;
}
</style>
